import { RouteRecordRaw } from 'vue-router';
import NProgress from 'nprogress';

import router from '@/router';
import store from '@/store';
import { GET_USER, GET_MENU, MENU_ACTION, REQ_CANCEL_ACTION } from '@/utils/Const';

import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router';

NProgress.inc(0.2);
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false });

const whiteList: string[] = ['/login'];

router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  NProgress.start();
  window.document.title = Object.keys(to.meta).length > 0 ? (to.meta?.title as string) : '核心系统';
  store.dispatch(`reqCancel/${REQ_CANCEL_ACTION}`);
  // 白名单放行
  if (whiteList.some((v) => v === to.path)) {
    next();
  } else if (!store.getters[`user/${GET_USER}`].accessToken) {
    //未登录 跳转到登录页
    NProgress.done();
    next(`/login?redirect=${to.path}`);
  } else {
    // 动态加载路由
    if (store.getters[`menu/${GET_MENU}`].length === 0) {
      const accessRoutes = await store.dispatch(`menu/${MENU_ACTION}`);
      accessRoutes.forEach((item) => {
        router.addRoute(item);
      });
      // 如果没有找到路由 默认跳转到首页
      router.addRoute({
        path: '/:pathMacth(.*)*',
        hidden: true,
        redirect: '/dashboard'
      } as RouteRecordRaw);
      next({ ...to });
    } else {
      next();
    }
  }
});
router.afterEach(() => {
  NProgress.done();
});
